package com.dingding.special.order.appoint.biz.special;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.Userdetail;
import com.dingding.common.core.beans.special.UserspecialorderT;
import com.dingding.common.core.cache.base.JedisUtil;
import com.dingding.common.core.cache.enums.DbEnum;
import com.dingding.common.core.push.enums.push.SpecialDriverPushEnum;
import com.dingding.common.core.push.factory.dtos.OrderDurationDTO;
import com.dingding.common.core.push.factory.request.IPushRequestFactory;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.special.order.appoint.biz.IAppointSpecialOrderService;
import com.dingding.special.order.appoint.cache.AppointOrderCache;
import com.dingding.special.order.appoint.dao.IAppointDao;
import com.dingding.special.user.customer.dao.ICustomerUserDao;
import com.dingding.special.user.driver.dao.IDriverUserDao;
import com.dingding.special.user.driver.dto.onlinedriver.OLineDriverDto;

/**
 * @Description:指派不是实时预约的订单的处理类
 * @author fengshuonan
 * @date 2016年8月23日 下午4:29:28
 * @version 叮叮搭车
 * @since 2.4
 */
@Component("appointUnRealOrderService")
public class AppointUnRealOrderServiceImpl implements IAppointSpecialOrderService {

	@Resource(name = "driverUserDao")
	private IDriverUserDao driverUserDao;

	@Resource(name = "customerUserDao")
	private ICustomerUserDao customerUserDao;

	@Resource(name = "specialDriverPushRequestFactory")
	private IPushRequestFactory pushRequestFactory;

	@Resource(name = "queueFacade")
	private IQueueFacade queueFacade;

	@Resource(name = "appointDao")
	private IAppointDao appointDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean appointSpecialOrder(UserspecialorderT userspecialorderT) {

		// 如果该订单不存在或者不是待指派状态，则返回成功，不让队列里继续存在
		if (appointDao.getSpecialOrderStatus(userspecialorderT.getSpecialOrderId()) != 1) {
			deleteRedisOrder(userspecialorderT);
			return true;
		}

		// 获取偏好为预约订单的所有在线司机
		List<OLineDriverDto> list = this.driverUserDao
				.getUnRealTimeOnlineDrivers(userspecialorderT.getPlaceOrderCity());

		// 判断此订单是否和在线车主所匹配
		for (OLineDriverDto dto : list) {
			boolean flag = this.isMacthing(userspecialorderT, dto);
			
			// 如果订单与司机的条件相匹配，则推送给司机这个单
			if (flag == true) {
				
				/**
				 * 判断司机近期30秒之内有没有被指派过订单
				 * 如果被指派过,则略过此人
				 */
				if(AppointOrderCache.haveAppointedRecently(dto.getUserId(),userspecialorderT.getSpecialOrderId())){
					continue;
				}
				
				//获取乘客详情
				Userdetail userdetail = this.customerUserDao.getUserdetail(userspecialorderT.getPlaceOrderUserId());

				// 乘客与司机不能是同一个人(防止刷单)
				if(dto.getTelPhone().equals(userdetail.getTellphone())){
					continue;
				}
				
				//获取订单的里程信息
				OrderDurationDTO orderDurationDTO = this.appointDao.getOrderDuration(dto,userspecialorderT);
				
				//发送订单推送给司机
				appointDriverOrder(userspecialorderT, dto, userdetail, orderDurationDTO);
			}
		}

		return false;
	}

	/**
	 * @Description 发送指派订单的推送给司机
	 * @param userspecialorderT 专车订单临时表中的订单
	 * @param dto 在线司机的详细信息封装
	 * @param userdetail 乘客的用户详情
	 * @param orderDurationDTO 订单历程信息的封装
	 * @author fengshuonan
	 */
	protected void appointDriverOrder(UserspecialorderT userspecialorderT, OLineDriverDto dto, Userdetail userdetail,
			OrderDurationDTO orderDurationDTO) {
		//推送给司机派单信息
		String pushBean = this.pushRequestFactory.createPushRequestString(
				SpecialDriverPushEnum.AppointSpecialOrderPush.toString(),
				dto.getUserId(), userdetail, userspecialorderT, orderDurationDTO);
		this.queueFacade.addPushToQueue(pushBean);
	}

	/**
	 * @modify by hufan 新添加约束条件（车辆等级）
	 */
	@Override
	public boolean isMacthing(UserspecialorderT userspecialorderT, OLineDriverDto oLineDriverDto) {
		
		//添加司机车辆类型( 1: 经济型 2：舒适型) 是否符合订单要求
		if (userspecialorderT.getVehicleLevelId() != oLineDriverDto.getVehicleLevelId()) {
			return false;
		}
		
		//判断司机是否有预约单
		boolean haveOrders = this.appointDao.isDriverHaveUnRealOrder(oLineDriverDto.getUserId());
		
		//如果有预约单，则不给司机匹配这个单
		if(haveOrders == true){
			return false;
		}

		// 乘客出发时间
		Date customerSetOutTime = userspecialorderT.getSetOutTime();

		// 车主的偏好天数
		Date startTime = oLineDriverDto.getStartTime();
		Date endTime = oLineDriverDto.getEndTime();
		
		boolean startTimeFlag = false;
		boolean endTimeFlag = false;
		
		if(startTime == null){
			startTimeFlag = true;
		}else{
			startTimeFlag = customerSetOutTime.after(startTime);
		}
		
		if(endTime == null){
			endTimeFlag = true;
		}else{
			endTimeFlag = customerSetOutTime.before(endTime);
		}
		
		if(startTimeFlag && endTimeFlag){
			return true;
		}else{
			return false;
		}
	}

	private void deleteRedisOrder(UserspecialorderT ordert){
		if(JedisUtil.isExistKey(ordert.getSpecialOrderId(), DbEnum.AppointOrderQueue.getValue())){
			JedisUtil.delKey(ordert.getSpecialOrderId(), DbEnum.AppointOrderQueue.getValue());
		}
	}

}
